package com.dingshi.security.adapter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dingshi.security.R;
import com.dingshi.security.RepairTrackActivity;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.RepairApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.Track;
import com.dingshi.security.util.Utils;

public class TrackAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private Context context;
	private ArrayList<Track> list;

	public TrackAdapter(Context context, ArrayList<Track> list) {
		this.context = context;
		this.list = list;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Track track = list.get(position);
		if (track == null) {
			return null;
		}
		final ViewHolder holder;

		if (convertView == null) {
			convertView = inflater.inflate(R.layout.track_item, null);
			holder = new ViewHolder();
			holder.trackItem = (LinearLayout) convertView
					.findViewById(R.id.track_item);
			holder.devicename = (TextView) convertView
					.findViewById(R.id.devicename);
			holder.time = (TextView) convertView.findViewById(R.id.timestamp);
			holder.status = (TextView) convertView.findViewById(R.id.status);
			holder.btn_look = (Button) convertView.findViewById(R.id.btn_look);
			holder.btn_del = (Button) convertView.findViewById(R.id.btn_del);
			holder.trackItem.setId(position);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		updateData(holder, track);

		OnClickListener clickListener = new OnClickListener() {

			@Override
			public void onClick(final View v) {
				switch (v.getId()) {
				case R.id.btn_look:
					 Intent intent = new Intent(context, RepairTrackActivity.class);
						intent.putExtra("status", list.get(((LinearLayout) v.getParent().getParent()).getId()).getStatus());

					intent.putExtra("oddNum", list.get(((LinearLayout) v.getParent().getParent()).getId()).getOddNum());
					context.startActivity(intent);

					break;
				case R.id.btn_del:
					new AlertDialog.Builder(context).setTitle("取消").setMessage("确认取消吗？")
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							cancelTrack(list.get(
									((LinearLayout) v.getParent().getParent()).getId()));
							
						}

						
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();
					break;

				default:
					break;
				}
			}
		};
		holder.btn_look.setOnClickListener(clickListener);
		holder.btn_del.setOnClickListener(clickListener);
		return convertView;
	}
	
	
	private void cancelTrack(final Track track) {
		RepairApi api = new RepairApi(context);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject obj = jsonEntity.getJSONObject("d");
							String result = obj.getString("r");
							if("1".equals(result)) {
								Utils.showToast(context, "取消成功");
								list.remove(track);
								TrackAdapter.this.notifyDataSetChanged();
							}else {
								Utils.showToast(context, "取消失败");
							}
							break;
						case 1:// 数组


							break;
						case -1:// 错误
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
			}
		});
		api.cancelTrack(1,SettingLoader.getGuardNum(context),track.getOddNum());
	}

	private void updateData(ViewHolder holder, Track track) {

		holder.devicename.setText(track.getArea());
		String start_time = track.getReportDate();
		if(!Utils.isNullOrEmpty(start_time)) {
			String[] split = start_time.split(" ");
			holder.time.setText(split[0]);
		}else {
			holder.time.setText(track.getReportDate());
		}
		
		if("1".equals(track.getStatus())) {
			holder.btn_del.setVisibility(View.VISIBLE);
		}else {
			holder.btn_del.setVisibility(View.GONE);
		}
		
		holder.status.setText(track.getDeviceName());
		
	}

	static class ViewHolder {
		public LinearLayout trackItem;
		public TextView devicename;
		public TextView time;
		public TextView status;
		public Button btn_look;
		public Button btn_del;
	}
}
